import axios from 'axios'
import $tip from '../components/able_mod/AbToolTip'
const apiUrl = process.env.NODE_ENV == 'development.' ? '//192.168.6.86:62553' : 'https://galaha.top/koaapi/'
const rootUrl = process.env.NODE_ENV == 'development' ? '//192.168.6.86:8080/mapdemo' : 'https://galaha.top/mapdemo/'

axios.defaults.baseURL = apiUrl
axios.defaults.withCredentials = true
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.timeout = 30000;

axios.interceptors.request.use(
  config => {
    let token = sessionStorage.getItem('token')
    if (token) {
      config.headers.Authorization = 'Bearer ' + token
    }
    return config;
  },
  error => {
    console.log(error)
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  response => {
    if (response.status == 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  error => {
    console.log(JSON.stringify(error))
    let _msg =  error.message || '服务器连接失败'
    if (error.response && error.response.status == 401) {
      _msg = 'token已过期，请重新登录'
      setTimeout(() => {
        window.location.href = rootUrl
      }, 2000);
    }
    $tip.message.open(_msg, 2500, 'error')
    setTimeout(() => {
      $tip.toast.close()
    }, 2000);
    return false;
  }
);

function http(url, method, data) {
  if (data.loading) $tip.toast.open('loading')
  let postdata = method == 'post' ? data : ''
  let getdata = method == 'get' ? data : ''
  return new Promise((resolve, reject) => {
    axios({
      method,
      url,
      data: postdata,
      params: getdata,
    })
    .then(res => {
      $tip.toast.close()
      let d = res.data
      // console.log(d)
      if (url == '/User/UserLogin') {
        if (d.data && d.data[0] && d.data[0].openId) sessionStorage.setItem('power_key',d.data[0].openId)
        if (d.data && d.data[1] && d.data[1].token) sessionStorage.setItem('token',d.data[1].token)
      }
      if (d.code == 40001) {
        $tip.message.open(d.msg, 2500, 'warning')
      }
      resolve(d)
    })
    .catch(err => {
      $tip.toast.close()
      console.log(err)
      $tip.message.open('服务器连接失败', 2500, 'error')
      reject(err)
    });
  })
}

export default {
  apiUrl, http,
}
